package com.scnu.edu.controller;

import com.alipay.api.AlipayApiException;
import com.scnu.edu.common.Result;
import com.scnu.edu.config.AliPayConfig;
import com.scnu.edu.entity.Order;
import com.scnu.edu.entity.User;
import com.scnu.edu.entity.Vip;
import com.scnu.edu.service.OrderService;
import com.scnu.edu.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private List<Vip> vipPackages; // 注入VIP套餐列表
    @RequestMapping("/orders")
    public String orders(Model model, HttpSession session) {
        // 从Session获取用户信息
        User user = (User) session.getAttribute("user");

        // 新增：用户未登录时重定向到登录页面
        if (user == null) {
            return "redirect:/login";
        }

        // 强制从数据库获取最新用户信息（包含VIP状态）
        User freshUser = userService.getById(user.getId());
        session.setAttribute("user", freshUser);
        model.addAttribute("user", freshUser);

        // 计算VIP剩余天数（如果有）
        if (freshUser.getVipExpireTime() != null) {
            long remainingDays = java.time.temporal.ChronoUnit.DAYS.between(
                    java.time.LocalDate.now(),
                    freshUser.getVipExpireTime().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate()
            );
            model.addAttribute("remainingDays", remainingDays);
        }

        // 查询用户订单列表
        List<Order> orders = orderService.lambdaQuery()
                .eq(Order::getUserId, freshUser.getId())
                .orderByDesc(Order::getCreateTime)
                .list();
        model.addAttribute("orders", orders);

        return "order/orders";
    }
    @RequestMapping("/vip")
    public String vip(Model model) {
        model.addAttribute("vip", vipPackages);
        return "order/vip";
    }

    @RequestMapping("/create")
    @ResponseBody
    public Map<String, Object> createOrder(Integer months, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return Map.of("code", 401, "message", "请先登录");
            }

            // 修正后 - 使用更准确的匹配方式
            Vip vip = vipPackages.stream()
                    .filter(p -> {
                        // 1个月: 30天左右，3个月: 90天左右，12个月: 365天
                        if (months == 1) return p.getDays() >= 28 && p.getDays() <= 31;
                        if (months == 3) return p.getDays() >= 88 && p.getDays() <= 92;
                        if (months == 12) return p.getDays() >= 360 && p.getDays() <= 370;
                        return false;
                    })
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("无效的套餐选择"));

            // 生成订单号
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String userStr = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String orderNum = time + userStr;

            Order order = new Order();
            order.setUserId(user.getId());
            order.setVipDays(vip.getDays());
            order.setAmount(vip.getPrice());
            order.setProductName(vip.getName());
            order.setStatus(0); // 待支付
            order.setCreateTime(new Date());
            order.setOrderNo(orderNum); // 关键修改：设置订单号

            boolean success = orderService.save(order);
            if (success) {
                return Map.of("code", 200, "message", "成功", "data", order.getId());
            } else {
                return Map.of("code", 500, "message", "订单创建失败");
            }
        } catch (Exception e) {
            return Map.of("code", 500, "message", "订单创建异常: " + e.getMessage());
        }
    }

    // 修正后（直接返回表单HTML）
    @PostMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam Integer orderId) {
        try {
            Order order = orderService.getById(orderId);
            if (order == null || order.getStatus() != 0) {
                return "<script>alert('订单不存在或已支付');window.history.back();</script>";
            }

            String form = aliPayConfig.sendRequestToAlipay(
                    order.getOrderNo(),
                    order.getAmount().doubleValue(),
                    "VIP会员(" + order.getVipDays() + "天)"
            );
            return form; // 直接返回表单HTML
        } catch (AlipayApiException e) {
            return "<script>alert('支付宝接口异常: " + e.getMessage() + "');window.history.back();</script>";
        }
    }


    @RequestMapping("/alipay/notify")
    @ResponseBody
    public String alipayNotify(
            @RequestParam("out_trade_no") String orderNo,
            @RequestParam("trade_status") String tradeStatus,
            HttpSession session) {

        // 1. 根据订单号查询订单
        Order order = orderService.lambdaQuery()
                .eq(Order::getOrderNo, orderNo)
                .one();

        if (order == null || !"TRADE_SUCCESS".equals(tradeStatus)) {
            return "fail";
        }

        // 2. 更新订单状态（防止重复处理）
        if (order.getStatus() == 0) {
            order.setStatus(1);
            order.setPayTime(new Date());
            orderService.updateById(order);
        }

        // 3. 更新用户VIP状态
        User user = userService.updateVipStatus(order.getUserId(), order.getVipDays());
        if (user != null) {
            session.setAttribute("user", user); // 更新Session
        }

        return "success";
    }

    @RequestMapping("/alipay/return")
    public String alipayReturn(@RequestParam("out_trade_no") String orderNo, Model model) {
        // 根据订单号查询
        Order order = orderService.lambdaQuery()
                .eq(Order::getOrderNo, orderNo)
                .one();

        if (order != null && order.getStatus() == 1) {
            model.addAttribute("message", "支付成功");
        } else {
            model.addAttribute("message", "支付失败");
        }
        return "order/result";
    }
}